/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.xstgongyi.eduaid.auth.CustomRealm;
import org.xstgongyi.eduaid.auth.CustomSessionManager;

/**
 * @author oldcrane<br/>
 * @created 2019-05-16
 */
@Configuration
public class ShiroConfig {

	@Bean
	public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(securityManager);

		shiroFilterFactoryBean.setLoginUrl("/unauthorized");
		shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");

		Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
		filterChainDefinitionMap.put("/public/**", "anon");
		filterChainDefinitionMap.put("/css/**", "anon");
		filterChainDefinitionMap.put("/js/**", "anon");
		filterChainDefinitionMap.put("/image/**", "anon");
		filterChainDefinitionMap.put("/students/**", "authc");
		filterChainDefinitionMap.put("/students-aids/**", "authc");
		filterChainDefinitionMap.put("/sponsors/**", "authc");
		filterChainDefinitionMap.put("/volunteers/**", "authc");
		filterChainDefinitionMap.put("/projects/**", "authc");
		filterChainDefinitionMap.put("/school-years/**", "authc");
		filterChainDefinitionMap.put("/semesters/**", "authc");
		filterChainDefinitionMap.put("/grades/**", "authc");
		filterChainDefinitionMap.put("/bank-accounts/**", "authc");
		filterChainDefinitionMap.put("/accounting-subjects/**", "authc");
		filterChainDefinitionMap.put("/users/**", "authc");
		filterChainDefinitionMap.put("/**", "anon");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

		return shiroFilterFactoryBean;
	}

	@Bean
	public SecurityManager securityManager() {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(getRealm());
		securityManager.setSessionManager(getSessionManager());
		return securityManager;
	}

	@Bean
	public CustomRealm getRealm() {
		return new CustomRealm();
	}

	@Bean
	public SessionManager getSessionManager() {
		SessionManager sessionManager = new CustomSessionManager();
		return sessionManager;
	}

}
